package net.csdn.business.notify.common.i18n;

import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.notify.common.enums.ResultCodeEnum;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.Locale;


/**
 * @ClassName LocaleMessageUtil
 * @Description 国际化消息获取工具
 * @Author zhangyl
 * @Date 2023/7/14 09:46
 */
@Slf4j
public class LocaleMessageUtil {
    private final static Locale EN_LOCALE = new Locale("en_US");
    private static MessageSource messageSource;

    private static MessageSource getSource() {
        if (ObjectUtils.isEmpty(messageSource)) {
            messageSource = SpringUtil.getBean("messageSource");
        }
        return messageSource;
    }

    public static String getMessage(ResultCodeEnum messageEnum) {
        try {
            return getSource().getMessage(messageEnum.getI18n(), null, messageEnum.getMsg(), LocaleContextHolder.getLocale());
        } catch (Exception ignore) {
        }
        return messageEnum.getMsg();
    }

    public static String getMessage(String msgProp) {
        try {
            return getSource().getMessage(msgProp, null, msgProp, LocaleContextHolder.getLocale());
        } catch (Exception ignore) {
        }
        return msgProp;
    }

    public static String getEnMessage(String msgProp) {
        try {
            return getSource().getMessage(msgProp, null, msgProp, EN_LOCALE);
        } catch (Exception ignore) {
        }
        return msgProp;
    }

}